<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function Node(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(2)
        var c = new Node(2)
        var d = new Node(3)
        var e = new Node(4)
        var f = new Node(4)
        var g = new Node(3)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g

        /* 
            比较的二叉树的左子树和右子树是不是相互翻转的，同时遍历左右两颗子树
            时间：O(n)
            空间：O(n)
        */
        var isSymmetric = function (root) {
            if (!root) return root
            return compare(root.left, root.right)
        };
        // 递归参数：左子树和右子树节点
        function compare(left, right) {
            // 退出条件：左右不相等，包括左右可能为空的情况
            if (left === null && right === null) {
                return true
            } else if (left !== null && right === null) {
                return false
            } else if (left === null && right !== null) {
                return false
            } else if (left !== right) {
                return false
            }

            // 遍历外侧，左子树left和右子树的right
            let outside = compare(left.left, right.right)
            // 遍历内侧，左子树right和右子树的left
            let inside = compare(left.right, right.left)
            // 左右是否相等
            const isSame = outside && inside
            // 返回布尔值
            return isSame
        }
        console.log(isSymmetric(a));
    </script>
</body>

</html>